package com.sunnay.advice;

import com.sunnay.annotation.SunayField;
import com.sunnay.util.FieldValidator;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;

import java.lang.reflect.Type;

@ControllerAdvice
public class ValidationRequestAdvice extends RequestBodyAdviceAdapter {

    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        SunayField fieldAnnotation = parameter.getParameterAnnotation(SunayField.class);
        if (fieldAnnotation != null) {
            //如果方法上存在Field注解就使用其中的FieldGroup 规则
            FieldValidator.validateFieldAndSuper(body,fieldAnnotation.fieldGroup());
            
        }else{
            FieldValidator.validateFieldAndSuper(body);
        }
        return super.afterBodyRead(body, inputMessage, parameter, targetType, converterType);
    }
}
